import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:myapp/generated/app_strings.dart';
import '../models/community_info.dart';
import '../services/community_storage_service.dart';
import '../services/community_export_service.dart';
import 'community_edit_page.dart';
import 'community_detail_page.dart';
import 'package:myapp/src/utils/app_baidu_map_utils.dart';
import 'package:flutter/rendering.dart';
import 'package:myapp/src/services/location_service.dart';
import 'package:uuid/uuid.dart';
import 'package:myapp/generated/l10n.dart';

///小区列表页面
class CommunityListPage extends StatefulWidget {
  final CommunityStorageService storageService;

  const CommunityListPage({
    Key? key,
    required this.storageService,
  }) : super(key: key);

  @override
  State<CommunityListPage> createState() => _CommunityListPageState();
}

class _CommunityListPageState extends State<CommunityListPage> {
  List<CommunityInfo> _communities = [];
  List<CommunityInfo> _filteredCommunities = [];
  bool _isLoading = true;
  String _searchQuery = '';
  final TextEditingController _searchController = TextEditingController();
  double? _currentLatitude;
  double? _currentLongitude;
  
  // 筛选条件
  bool _filterAllowDelivery = false;
  bool _filterNotAllowDelivery = false;
  bool _filterHasDoorControl = false;
  bool _filterNoDoorControl = false;
  bool _filterHasElevator = false;
  bool _filterNoElevator = false;
  bool _filterElevatorNeedCard = false;
  bool _filterElevatorNoNeedCard = false;
  bool _filterYuyaoJiangnanSouth = false;
  bool _filterNingciEastNorth = false;
  bool _filterHongtang = false;
  bool _filterMixc = false;
  bool _filterEasyDelivery = false;
  bool _filterHardDelivery = false;
  bool _filterBusiness = false;
  bool _filterNotBusiness = false;
  bool _filterHasDeliveryCabinet = false;
  bool _isFilterExpanded = false;

  @override
  void initState() {
    super.initState();
    _loadCommunities();
    _getCurrentLocation();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadCommunities() async {
    setState(() => _isLoading = true);
    try {
      final communities = await widget.storageService.getAllCommunities();
      setState(() {
        _communities = communities;
        _applyFilters();
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载数据失败: $e')),
      );
    }
  }

  Future<void> _getCurrentLocation() async {
    try {
      final location = await LocationService.getCurrentLocation(context);
      if (location != null) {
        setState(() {
          _currentLatitude = location.latitude;
          _currentLongitude = location.longitude;
          // 获取位置后立即重新排序
          _applyFilters();
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('获取当前位置失败: $e')),
        );
      }
    }
  }

  String _getDistanceText(CommunityInfo community) {
    if (_currentLatitude == null || _currentLongitude == null || 
        community.latitude == null || community.longitude == null) {
      return '距离未知';
    }

    final distance = AppBaiduMapUtils.getDistance(
      _currentLongitude!,
      _currentLatitude!,
      community.longitude!,
      community.latitude!,
    );

    if (distance < 1000) {
      return '${distance.toStringAsFixed(0)}米';
    } else {
      return '${(distance / 1000).toStringAsFixed(1)}公里';
    }
  }

  void _applyFilters() {
    setState(() {
      _filteredCommunities = _communities.where((community) {
        if (_searchQuery.isNotEmpty) {
          if (!community.name.toLowerCase().contains(_searchQuery.toLowerCase())) {
            return false;
          }
        }

        if (_filterAllowDelivery && !community.allowDelivery) return false;
        if (_filterNotAllowDelivery && community.allowDelivery) return false;
        if (_filterHasDoorControl && !community.hasDoorControl) return false;
        if (_filterNoDoorControl && community.hasDoorControl) return false;
        if (_filterHasElevator && !community.hasElevator) return false;
        if (_filterNoElevator && community.hasElevator) return false;
        if (_filterElevatorNeedCard && (!community.hasElevator || !community.elevatorNeedCard)) return false;
        if (_filterElevatorNoNeedCard && (!community.hasElevator || community.elevatorNeedCard)) return false;
        if (_filterYuyaoJiangnanSouth && !community.isInYuyaoJiangnanSouth) return false;
        if (_filterNingciEastNorth && !community.isInNingciEastNorth) return false;
        if (_filterHongtang && !community.isInHongtang) return false;
        if (_filterMixc && !community.isNearMixc) return false;
        if (_filterEasyDelivery && !community.isEasyDelivery) return false;
        if (_filterHardDelivery && !community.isHardDelivery) return false;
        if (_filterBusiness && !community.isBusiness) return false;
        if (_filterNotBusiness && community.isBusiness) return false;
        if (_filterHasDeliveryCabinet && !community.hasDeliveryCabinet) return false;

        return true;
      }).toList();

      // 按距离排序
      if (_currentLatitude != null && _currentLongitude != null) {
        _filteredCommunities.sort((a, b) {
          // 如果小区没有位置信息，将其排在最后
          if (a.latitude == null || a.longitude == null) return 1;
          if (b.latitude == null || b.longitude == null) return -1;

          // 计算距离
          final distanceA = AppBaiduMapUtils.getDistance(
            _currentLongitude!,
            _currentLatitude!,
            a.longitude!,
            a.latitude!,
          );
          final distanceB = AppBaiduMapUtils.getDistance(
            _currentLongitude!,
            _currentLatitude!,
            b.longitude!,
            b.latitude!,
          );

          // 按距离从小到大排序
          return distanceA.compareTo(distanceB);
        });
      }
    });
  }

  void _resetFilters() {
    setState(() {
      _searchQuery = '';
      _searchController.clear();
      _filterAllowDelivery = false;
      _filterNotAllowDelivery = false;
      _filterHasDoorControl = false;
      _filterNoDoorControl = false;
      _filterHasElevator = false;
      _filterNoElevator = false;
      _filterElevatorNeedCard = false;
      _filterElevatorNoNeedCard = false;
      _filterYuyaoJiangnanSouth = false;
      _filterNingciEastNorth = false;
      _filterHongtang = false;
      _filterMixc = false;
      _filterEasyDelivery = false;
      _filterHardDelivery = false;
      _filterBusiness = false;
      _filterNotBusiness = false;
      _filterHasDeliveryCabinet = false;
      _applyFilters();
    });
  }

  Widget _buildFilterChip({
    required String label,
    required bool value,
    required ValueChanged<bool?> onChanged,
  }) {
    return FilterChip(
      label: Text(
        label,
        style: const TextStyle(fontSize: 11),
      ),
      selected: value,
      onSelected: (selected) {
        setState(() {
          onChanged(selected);
          _applyFilters();
        });
      },
      selectedColor: Theme.of(context).primaryColor.withOpacity(0.2),
      checkmarkColor: Theme.of(context).primaryColor,
      padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 0),
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
      backgroundColor: Colors.grey.withOpacity(0.1),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
        side: BorderSide(
          color: value ? Theme.of(context).primaryColor.withOpacity(0.5) : Colors.grey.withOpacity(0.3),
        ),
      ),
    );
  }

  Future<void> _exportData() async {
    if (_filteredCommunities.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有数据可导出')),
      );
      return;
    }

    try {
      final filePath = await CommunityExportService.exportToJson(_filteredCommunities);
      if (filePath != null) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('数据已导出到: $filePath\t文件路径已复制。')),
          );
          TextUtils.copyText(filePath);
          AioPlugin.shareFile(context, filePath); //数据文件分享。
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('导出失败，请检查存储权限')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _deleteCommunity(CommunityInfo community) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppStrings.of(context).confirmDelete),
        content: Text(AppStrings.of(context).confirmDeleteCommunity(community.name)),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text(AppStrings.of(context).cancel),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text(AppStrings.of(context).delete),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      await widget.storageService.deleteCommunity(community.id);
      _loadCommunities();
    }
  }

  Future<void> _deleteAllCommunities() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppStrings.of(context).confirmDelete),
        content: Text(AppStrings.of(context).confirmDeleteAllCommunities),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text(AppStrings.of(context).cancel),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: Text(AppStrings.of(context).delete),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      await widget.storageService.deleteAllCommunities();
      _loadCommunities();
    }
  }

  void _navigateToCommunity(CommunityInfo community) {
    if (community.latitude != null && community.longitude != null) {
      AioPlugin.goMap(
        context,
        community.latitude.toString(),
        community.longitude.toString(),
        community.name,
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(AppStrings.of(context).noLocationInfo)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppStrings.of(context).communityManagement),
        actions: [
          IconButton(
            icon: const Icon(Icons.delete_sweep),
            onPressed: _deleteAllCommunities,
            tooltip: AppStrings.of(context).deleteAllCommunities,
          ),
          IconButton(
            icon: const Icon(Icons.my_location),
            onPressed: _getCurrentLocation,
            tooltip: '更新位置',
          ),
          IconButton(
            icon: const Icon(Icons.file_download),
            onPressed: _exportData,
            tooltip: AppStrings.of(context).exportData,
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              final result = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => CommunityEditPage(
                    storageService: widget.storageService,
                  ),
                ),
              );
              if (result == true) {
                _loadCommunities();
              }
            },
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: AppStrings.of(context).searchCommunityName,
                prefixIcon: const Icon(Icons.search, size: 20),
                suffixIcon: _searchQuery.isNotEmpty
                    ? IconButton(
                        icon: const Icon(Icons.clear, size: 20),
                        onPressed: () {
                          setState(() {
                            _searchQuery = '';
                            _searchController.clear();
                            _applyFilters();
                          });
                        },
                      )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                isDense: true,
              ),
              onChanged: (value) {
                setState(() {
                  _searchQuery = value;
                  _applyFilters();
                });
              },
            ),
          ),
          Container(
            padding: const EdgeInsets.fromLTRB(12, 6, 12, 6),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                      decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.filter_list,
                            size: 14,
                            color: Theme.of(context).primaryColor,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            AppStrings.of(context).filterConditions,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              color: Theme.of(context).primaryColor,
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 8),
                    if (_filterAllowDelivery ||
                        _filterNotAllowDelivery ||
                        _filterHasDoorControl ||
                        _filterNoDoorControl ||
                        _filterHasElevator ||
                        _filterNoElevator ||
                        _filterElevatorNeedCard ||
                        _filterElevatorNoNeedCard ||
                        _filterYuyaoJiangnanSouth ||
                        _filterNingciEastNorth ||
                        _filterHongtang ||
                        _filterMixc ||
                        _filterEasyDelivery ||
                        _filterHardDelivery ||
                        _filterBusiness ||
                        _filterNotBusiness ||
                        _filterHasDeliveryCabinet)
                      TextButton.icon(
                        onPressed: _resetFilters,
                        icon: const Icon(Icons.clear, size: 14),
                        label: Text(
                          AppStrings.of(context).clearFilters,
                          style: const TextStyle(fontSize: 12),
                        ),
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ),
                      ),
                    const Spacer(),
                    IconButton(
                      icon: Icon(
                        _isFilterExpanded ? Icons.expand_less : Icons.expand_more,
                        size: 18,
                      ),
                      onPressed: () {
                        setState(() {
                          _isFilterExpanded = !_isFilterExpanded;
                        });
                      },
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      style: IconButton.styleFrom(
                        foregroundColor: Theme.of(context).primaryColor,
                      ),
                    ),
                  ],
                ),
                if (_isFilterExpanded) ...[
                  const SizedBox(height: 4),
                  Wrap(
                    spacing: 4,
                    runSpacing: 4,
                    children: [
                      _buildFilterChip(
                        label: AppStrings.of(context).allowDeliveryBike,
                        value: _filterAllowDelivery,
                        onChanged: (value) {
                          setState(() {
                            _filterAllowDelivery = value ?? false;
                            if (_filterAllowDelivery) _filterNotAllowDelivery = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).notAllowDeliveryBike,
                        value: _filterNotAllowDelivery,
                        onChanged: (value) {
                          setState(() {
                            _filterNotAllowDelivery = value ?? false;
                            if (_filterNotAllowDelivery) _filterAllowDelivery = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).hasDoorControl,
                        value: _filterHasDoorControl,
                        onChanged: (value) {
                          setState(() {
                            _filterHasDoorControl = value ?? false;
                            if (_filterHasDoorControl) _filterNoDoorControl = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).noDoorControl,
                        value: _filterNoDoorControl,
                        onChanged: (value) {
                          setState(() {
                            _filterNoDoorControl = value ?? false;
                            if (_filterNoDoorControl) _filterHasDoorControl = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).hasElevator,
                        value: _filterHasElevator,
                        onChanged: (value) {
                          setState(() {
                            _filterHasElevator = value ?? false;
                            if (_filterHasElevator) _filterNoElevator = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).noElevator,
                        value: _filterNoElevator,
                        onChanged: (value) {
                          setState(() {
                            _filterNoElevator = value ?? false;
                            if (_filterNoElevator) _filterHasElevator = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).elevatorNeedCard,
                        value: _filterElevatorNeedCard,
                        onChanged: (value) {
                          setState(() {
                            _filterElevatorNeedCard = value ?? false;
                            if (_filterElevatorNeedCard) _filterElevatorNoNeedCard = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).elevatorNoNeedCard,
                        value: _filterElevatorNoNeedCard,
                        onChanged: (value) {
                          setState(() {
                            _filterElevatorNoNeedCard = value ?? false;
                            if (_filterElevatorNoNeedCard) _filterElevatorNeedCard = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).yuyaoJiangnanSouth,
                        value: _filterYuyaoJiangnanSouth,
                        onChanged: (value) => _filterYuyaoJiangnanSouth = value ?? false,
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).ningciEastNorth,
                        value: _filterNingciEastNorth,
                        onChanged: (value) => _filterNingciEastNorth = value ?? false,
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).hongtang,
                        value: _filterHongtang,
                        onChanged: (value) => _filterHongtang = value ?? false,
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).nearMixc,
                        value: _filterMixc,
                        onChanged: (value) => _filterMixc = value ?? false,
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).easyDelivery,
                        value: _filterEasyDelivery,
                        onChanged: (value) => _filterEasyDelivery = value ?? false,
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).hardDelivery,
                        value: _filterHardDelivery,
                        onChanged: (value) => _filterHardDelivery = value ?? false,
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).isBusiness,
                        value: _filterBusiness,
                        onChanged: (value) {
                          setState(() {
                            _filterBusiness = value ?? false;
                            if (_filterBusiness) _filterNotBusiness = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).notBusiness,
                        value: _filterNotBusiness,
                        onChanged: (value) {
                          setState(() {
                            _filterNotBusiness = value ?? false;
                            if (_filterNotBusiness) _filterBusiness = false;
                            _applyFilters();
                          });
                        },
                      ),
                      _buildFilterChip(
                        label: AppStrings.of(context).hasDeliveryCabinet,
                        value: _filterHasDeliveryCabinet,
                        onChanged: (value) => _filterHasDeliveryCabinet = value ?? false,
                      ),
                    ],
                  ),
                ],
              ],
            ),
          ),
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _filteredCommunities.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(
                              Icons.info_outline,
                              size: 64,
                              color: Colors.grey,
                            ),
                            const SizedBox(height: 16),
                            Text(
                              AppStrings.of(context).noCommunityInfo,
                              style: const TextStyle(
                                fontSize: 18,
                                color: Colors.grey,
                              ),
                            ),
                            const SizedBox(height: 16),
                            ElevatedButton.icon(
                              onPressed: () => _navigateToEditPage(),
                              icon: const Icon(Icons.add),
                              label: Text(AppStrings.of(context).addCommunity),
                            ),
                          ],
                        ),
                      )
                    : Column(
                        children: [
                          Expanded(
                            child: ListView.builder(
                              itemCount: _filteredCommunities.length,
                              itemBuilder: (context, index) {
                                final community = _filteredCommunities[index];
                                return Card(
                                  margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                                  child: InkWell(
                                    onTap: () async {
                                      final result = await Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => CommunityDetailPage(
                                            community: community,
                                          ),
                                        ),
                                      );
                                      if (result == true) {
                                        _loadCommunities();
                                      }
                                    },
                                    child: Padding(
                                      padding: const EdgeInsets.all(8),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            children: [
                                              Container(
                                                width: 24,
                                                height: 24,
                                                decoration: BoxDecoration(
                                                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                                                  borderRadius: BorderRadius.circular(4),
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    '${index + 1}',
                                                    style: TextStyle(
                                                      fontSize: 12,
                                                      color: Theme.of(context).primaryColor,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                              const SizedBox(width: 8),
                                              Expanded(
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    GestureDetector(
                                                      onTap: () {
                                                        Clipboard.setData(ClipboardData(text: community.name));
                                                        ScaffoldMessenger.of(context).showSnackBar(
                                                          SnackBar(
                                                            content: Text(AppStrings.of(context).communityNameCopied),
                                                            duration: const Duration(seconds: 1),
                                                          ),
                                                        );
                                                      },
                                                      child: Text(
                                                        community.name,
                                                        style: const TextStyle(
                                                          fontSize: 14,
                                                          fontWeight: FontWeight.bold,
                                                        ),
                                                      ),
                                                    ),
                                                    const SizedBox(height: 2),
                                                    Text(
                                                      _getDistanceText(community),
                                                      style: TextStyle(
                                                        fontSize: 12,
                                                        color: Colors.grey[600],
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Row(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  IconButton(
                                                    icon: const Icon(Icons.navigation, size: 18),
                                                    onPressed: () => _navigateToCommunity(community),
                                                    padding: EdgeInsets.zero,
                                                    constraints: const BoxConstraints(),
                                                    style: IconButton.styleFrom(
                                                      foregroundColor: Colors.blue,
                                                    ),
                                                    tooltip: '导航',
                                                  ),
                                                  const SizedBox(width: 8),
                                                  IconButton(
                                                    icon: const Icon(Icons.edit, size: 18),
                                                    onPressed: () => _navigateToEditPage(community),
                                                    padding: EdgeInsets.zero,
                                                    constraints: const BoxConstraints(),
                                                    style: IconButton.styleFrom(
                                                      foregroundColor: Colors.blue,
                                                    ),
                                                  ),
                                                  const SizedBox(width: 8),
                                                  IconButton(
                                                    icon: const Icon(Icons.delete, size: 18),
                                                    onPressed: () => _deleteCommunity(community),
                                                    padding: EdgeInsets.zero,
                                                    constraints: const BoxConstraints(),
                                                    style: IconButton.styleFrom(
                                                      foregroundColor: Colors.red,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                          const SizedBox(height: 4),
                                          GestureDetector(
                                            onTap: () {
                                              Clipboard.setData(ClipboardData(text: community.address));
                                              ScaffoldMessenger.of(context).showSnackBar(
                                                SnackBar(
                                                  content: Text(AppStrings.of(context).communityAddressCopied),
                                                  duration: const Duration(seconds: 1),
                                                ),
                                              );
                                            },
                                            child: Text(
                                              community.address,
                                              style: const TextStyle(
                                                fontSize: 12,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ),
                                          const SizedBox(height: 4),
                                          Wrap(
                                            spacing: 4,
                                            runSpacing: 4,
                                            children: [
                                              _buildFeatureChip(
                                                icon: Icons.delivery_dining,
                                                label: AppStrings.of(context).deliveryBike,
                                                enabled: community.allowDelivery,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.elevator,
                                                label: AppStrings.of(context).elevator,
                                                enabled: community.hasElevator,
                                              ),
                                              if (community.hasElevator)
                                                _buildFeatureChip(
                                                  icon: Icons.credit_card,
                                                  label: AppStrings.of(context).needCard,
                                                  enabled: community.elevatorNeedCard,
                                                ),
                                              _buildFeatureChip(
                                                icon: Icons.door_front_door,
                                                label: AppStrings.of(context).doorControl,
                                                enabled: community.hasDoorControl,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.location_on,
                                                label: AppStrings.of(context).yuyaoJiangnanSouth,
                                                enabled: community.isInYuyaoJiangnanSouth,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.location_on,
                                                label: AppStrings.of(context).ningciEastNorth,
                                                enabled: community.isInNingciEastNorth,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.location_on,
                                                label: AppStrings.of(context).hongtang,
                                                enabled: community.isInHongtang,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.location_on,
                                                label: AppStrings.of(context).nearMixc,
                                                enabled: community.isNearMixc,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.thumb_up,
                                                label: AppStrings.of(context).easyDelivery,
                                                enabled: community.isEasyDelivery,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.thumb_down,
                                                label: AppStrings.of(context).hardDelivery,
                                                enabled: community.isHardDelivery,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.store,
                                                label: AppStrings.of(context).business,
                                                enabled: community.isBusiness,
                                              ),
                                              _buildFeatureChip(
                                                icon: Icons.inventory_2,
                                                label: AppStrings.of(context).deliveryCabinet,
                                                enabled: community.hasDeliveryCabinet,
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(
                              left: 16,
                              right: 16,
                              top: 8,
                              bottom: 8 + MediaQuery.of(context).padding.bottom,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.05),
                                  blurRadius: 4,
                                  offset: const Offset(0, -2),
                                ),
                              ],
                            ),
                            child: Row(
                              children: [
                                Text(
                                  AppStrings.of(context).totalCount(_filteredCommunities.length),
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context).primaryColor,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
          ),
        ],
      ),
    );
  }

  void _navigateToEditPage([CommunityInfo? community]) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CommunityEditPage(
          storageService: widget.storageService,
          community: community,
        ),
      ),
    );

    if (result == true) {
      _loadCommunities();
    }
  }

  void _navigateToDetailPage(CommunityInfo community) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CommunityDetailPage(community: community),
      ),
    );
  }

  Widget _buildFeatureChip({
    required IconData icon,
    required String label,
    required bool enabled,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: enabled ? Colors.green.withOpacity(0.1) : Colors.grey.withOpacity(0.1),
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: enabled ? Colors.green.withOpacity(0.5) : Colors.grey.withOpacity(0.5),
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 14,
            color: enabled ? Colors.green : Colors.grey,
          ),
          const SizedBox(width: 2),
          Text(
            label,
            style: TextStyle(
              fontSize: 11,
              color: enabled ? Colors.green : Colors.grey,
            ),
          ),
        ],
      ),
    );
  }
}
